#!/usr/bin/python

######################################################
#
# Read in trajectory file of storms (one line per time step) and
# summarize information for each storm. Write to standard out.
#
######################################################

# python traj_summarize.py traj_1980 > traj_1_past_summary

#
# MODULES
#
import sys
import os
import string

import math
import warnings

fin = 'traj_stat'

if len(sys.argv) < 2:
    print 'Usage: %s <trajectory file>' % sys.argv[0]
    print
    raise SystemExit
else:
    fin = sys.argv[1]

# open trajectory file
assert os.path.exists(fin),"traj_summarize: file not found"
try:
    f = open(fin, 'r')
except IOError:
    print >> sys.stderr, "traj_summarize: could not open %s" % fin
    exit

cyclones = dict()

t=0
lon=-1
lat=-1
id=1
line = f.readline()
while line:
     elems = string.split(line)

     if (elems[0] == 'start'):
#         cyclones.append(id)

          # number of storms in this trajectory
          length = int(elems[1])

          # start date/time
          date1 = elems[2] # start year
          date2 = elems[3] # start month
          date3 = elems[4] # start day
          date4 = elems[5] # start hour

          # fraction of time steps passing thickness and warm core criteria
          pthick = elems[6]
          ptwc = elems[7]
          
          maxwind = -1.0
          minpsl = 100000.0

     # read storm info         
     else:
          if (lon<0):
               lon = elems[0]
          if (lat<0):
               lat = elems[1]

          wind = float(elems[2])
          psl = float(elems[3])
          
          if (wind>maxwind):
               maxwind = wind
          if (psl<minpsl):
               minpsl = psl
          t = t+1

     if (t==length):
          cyclones[id] = [date1, date2, date3, date4, lon, lat, maxwind, minpsl, length, pthick, ptwc]
          id = id+1
          t=0
          lon=-1
          lat=-1
          
          
     line = f.readline()


f.close()

# print formatted list
print('ID \tYEAR \tMO \tDAY \tHR \tLONG \tLAT \tMAXWIND \tMINPSL \t\t\tLENGTH\tTHICK\tWARMCORE')
for id in cyclones:
     val = cyclones[id]
     print '%d \t%4d \t%d \t%d \t%d \t%0.2f \t%0.2f \t%0.2f \t\t%7.2f \t\t%d\t%0.2f\t%0.2f' % (id,
            int(val[0]), int(val[1]), int(val[2]), int(val[3]),
            float(val[4]), float(val[5]),
            float(val[6]), float(val[7]), int(val[8]), float(val[9]), float(val[10]))
